package com.fht.controller.promotion;


import com.fht.entity.*;
import com.fht.enums.ManagermentSystemEnum;
import com.fht.exception.ManagermentSystemException;
import com.fht.from.promotionFrom;
import com.fht.service.food.FoodCategoryService;
import com.fht.service.food.MerchantsInformationService;
import com.fht.service.promotion.PromotionMealHotCategoryService;
import com.fht.service.promotion.PromotionMealHotParticularsService;
import com.fht.service.promotion.PromotionMealHotService;
import com.fht.util.GenerateOrdersIDUtil;
import com.fht.util.ResultVOUtil;
import com.fht.util.UnitConversionUtil;
import com.fht.vo.LayUITableVO;
import com.fht.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fht.constant.ManagermentSystemConstant.PROMOTION_MEAL_HOT_PARTICULARS_MAP;
import static com.fht.constant.ManagermentSystemConstant.PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP;

@Controller
@Slf4j
@RequestMapping("/promotion/mealHot")
public class PromotionMealHotController {


    @Autowired
    public PromotionMealHotService promotionMealHotService;

    @Autowired
    public PromotionMealHotCategoryService promotionMealHotCategoryService;

    @Autowired
    public PromotionMealHotParticularsService promotionMealHotParticularsService;


    @Autowired
    public FoodCategoryService foodCategoryService;

    @Autowired
    public MerchantsInformationService merchantsInformationService;


    //菜品类别展示
    @GetMapping("/index")
    public String index(Model model){

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);

        return "promotion/mealHot/index";

    }


    //获取菜品类别信息
    @GetMapping("/list")
    @ResponseBody
    public LayUITableVO<List<PromotionMealHot>> list (@RequestParam(defaultValue = "1") Integer page,
                                                           @RequestParam(defaultValue = "10") Integer limit,
                                                           promotionFrom from){
        Map<String ,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("limit",limit);
        map.put("from",from);

        LayUITableVO<List<PromotionMealHot>> vo = promotionMealHotService.findPage(map);


        return vo;
    }


    //跳转到修改页面
    @GetMapping("/edit-ui")
    public String editUI(String id,Model model){

        PromotionMealHot promotionMealHot =  promotionMealHotService.selectById(id);
        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();

        List<PromotionMealHotCategory> promotionMealHotCategoryList = promotionMealHotCategoryService.selectAll();

        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("promotionMealHot",promotionMealHot);
        model.addAttribute("promotionMealHotCategoryList",promotionMealHotCategoryList);

        return "promotion/mealHot/edit";

    }

    //查询订单详情信息，并放入map缓存中
    @GetMapping("/recordList")
    @ResponseBody
    public LayUITableVO<List<PromotionMealHotParticulars>> ordersList (@RequestParam(defaultValue = "1") Integer page,
                                                                       @RequestParam(defaultValue = "10") Integer limit,
                                                                       String id){

        LayUITableVO<List<PromotionMealHotParticulars>> vo = promotionMealHotParticularsService.findPageById(id);

        PROMOTION_MEAL_HOT_PARTICULARS_MAP.put(id,vo);

        return vo;
    }


    //修改map缓存中的数据，并重新计算价格总和
    @PostMapping("/editMap")
    @ResponseBody
    public ResultVO editMap (PromotionMealHotParticulars promotionMealHotParticulars){

        LayUITableVO<List<PromotionMealHotParticulars>> listLayUITableVO = PROMOTION_MEAL_HOT_PARTICULARS_MAP.get(promotionMealHotParticulars.getId());
        List<PromotionMealHotParticulars> dataList = listLayUITableVO.getData();

        for (PromotionMealHotParticulars data : dataList) {
            int id2 = data.getRecordId();
            int id1 = promotionMealHotParticulars.getRecordId();
            if (id1 ==id2){
            data.setRecordNum(promotionMealHotParticulars.getRecordNum());

            data.setTotalPriceString(UnitConversionUtil.conversion(promotionMealHotParticulars.getRecordNum()* UnitConversionUtil.conversion(promotionMealHotParticulars.getPriceString())));
            }
        }


        return ResultVOUtil.ok();
    }

    //刷新订单详情信息，将修改好的新的价格总和给页面
    @GetMapping("/refresh")
    @ResponseBody
    public LayUITableVO<List<PromotionMealHotParticulars>> refresh (@RequestParam(defaultValue = "1") Integer page,
                                                                         @RequestParam(defaultValue = "10") Integer limit,
                                                                         String id){


        return PROMOTION_MEAL_HOT_PARTICULARS_MAP.get(id);
    }

    //删除map缓存中的指定的一条详情信息
    @PostMapping("/delMap")
    @ResponseBody
    public ResultVO delMap (String id,String recordId){

        LayUITableVO<List<PromotionMealHotParticulars>> listLayUITableVO = PROMOTION_MEAL_HOT_PARTICULARS_MAP.get(id);

        List<PromotionMealHotParticulars> dataList = listLayUITableVO.getData();

        for (PromotionMealHotParticulars data : dataList) {
            int recordId1 = data.getRecordId();
            int recordId2 = Integer.valueOf(recordId);
            if (recordId1==recordId2){

                dataList.remove(data);
                break;
            }
        }

        promotionMealHotParticularsService.deleteByIdAndRecordId(id,recordId);
        return ResultVOUtil.ok();
    }

    //选择菜品原料页面
    @GetMapping("/edit-chooseRecord-ui")
    public String editChooseMaterialUI(String merchantsId,String id,Model model){


        List<FoodCategory> foodCategoryList = foodCategoryService.selectBymerchantsId(merchantsId);
        model.addAttribute("foodCategoryList",foodCategoryList);
        model.addAttribute("merchantsId",merchantsId);
        model.addAttribute("id",id);

        return "promotion/mealHot/chooseRecord";

    }


    //将选中的菜品原料信息放入到map缓存中
    @PostMapping("/addMap")
    @ResponseBody
    public ResultVO addMap ( @RequestBody Map<String,Object> map){


        List<Map<String,String>> listMap = (List<Map<String,String>>) map.get("data");
        String id = (String) map.get("id");

        LayUITableVO<List<PromotionMealHotParticulars>> listLayUITableVO = PROMOTION_MEAL_HOT_PARTICULARS_MAP.get(id);
        List<PromotionMealHotParticulars> dataList = listLayUITableVO.getData();

        List<String > recordList = new ArrayList<>();
        for (PromotionMealHotParticulars promotionMealHotParticulars : dataList) {
            recordList.add(String.valueOf(promotionMealHotParticulars.getRecordId()));
        }


        for (Map<String, String> stringStringMap : listMap) {
            PromotionMealHotParticulars promotionMealHotParticulars = new PromotionMealHotParticulars();
            try {
                BeanUtils.populate(promotionMealHotParticulars,stringStringMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            if (recordList.size() !=0 && recordList.contains(promotionMealHotParticulars.getId()))
                continue;
            promotionMealHotParticulars.setRecordName(stringStringMap.get("foodName"));
            promotionMealHotParticulars.setRecordId(Integer.valueOf(promotionMealHotParticulars.getId()));
            promotionMealHotParticulars.setId(id);
            promotionMealHotParticulars.setRecordNum(0);
            promotionMealHotParticulars.setTotalPriceString(null);
            dataList.add(promotionMealHotParticulars);
        }



        return ResultVOUtil.ok();
    }

    //取消操作，删除map中的缓存
    @PostMapping("/delAllMap")
    @ResponseBody
    public ResultVO delAllMap (String id){


        Set<String> keySet = PROMOTION_MEAL_HOT_PARTICULARS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(id)){
                PROMOTION_MEAL_HOT_PARTICULARS_MAP.remove(id);
            }
        }


        return ResultVOUtil.ok();
    }

    //提交操作（修改或添加），判断订单详情的数据完整性，分别存入两表中，移除map缓存
    @PostMapping("/saveMap")
    @ResponseBody
    public ResultVO saveMap (PromotionMealHot promotionMealHot){

        LayUITableVO<List<PromotionMealHotParticulars>> listLayUITableVO = PROMOTION_MEAL_HOT_PARTICULARS_MAP.get(promotionMealHot.getId());
        List<PromotionMealHotParticulars> dataList = listLayUITableVO.getData();
        if (dataList.size()==0){
            throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
        }

        for (PromotionMealHotParticulars data : dataList) {
            if (data.getRecordNum() == 0){
                throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
            }
        }

        promotionMealHotService.update(promotionMealHot);

        promotionMealHotParticularsService.save(dataList);


        Set<String> keySet = PROMOTION_MEAL_HOT_PARTICULARS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(promotionMealHot.getId())){
                PROMOTION_MEAL_HOT_PARTICULARS_MAP.remove(promotionMealHot.getId());
            }
        }



        return ResultVOUtil.ok();
    }

    //跳转到添加页面
    @GetMapping("/add-ui")
    public String addUI(String merchantsId,Model model){

        PromotionMealHot promotionMealHot = new PromotionMealHot();

        promotionMealHot.setId("MH"+ GenerateOrdersIDUtil.generateOrdersID(1001));
        promotionMealHot.setMerchantsId(Integer.valueOf(merchantsId));


        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();


        List<PromotionMealHotCategory> promotionMealHotCategoryList = promotionMealHotCategoryService.selectAll();

        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("promotionMealHot",promotionMealHot);
        model.addAttribute("promotionMealHotCategoryList",promotionMealHotCategoryList);



        return "promotion/mealHot/add";

    }

    //跳转到修改页面
    @GetMapping("/show-ui")
    public String showUI(String id,Model model){

        PromotionMealHot promotionMealHot =  promotionMealHotService.selectById(id);
        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();

        List<PromotionMealHotCategory> promotionMealHotCategoryList = promotionMealHotCategoryService.selectAll();

        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("promotionMealHot",promotionMealHot);
        model.addAttribute("promotionMealHotCategoryList",promotionMealHotCategoryList);

        return "promotion/mealHot/show";

    }

    //删除
    @PostMapping("/del")
    @ResponseBody
    public ResultVO del (String id){

        promotionMealHotService.deleteById(id);

        promotionMealHotParticularsService.deleteById(id);


        return ResultVOUtil.ok();
    }

}
